package cn.doctorpda.conference.presenter;

import org.json.JSONException;
import org.json.JSONObject;

import cn.doctorpda.conference.MyApplication;
import cn.doctorpda.conference.bean.Msg;
import cn.doctorpda.conference.bean.User;
import cn.doctorpda.conference.config.AppConfig;
import cn.doctorpda.conference.config.NetConfig;
import cn.doctorpda.conference.localstore.ClientInfo;
import cn.doctorpda.conference.localstore.UserInfo;
import cn.doctorpda.conference.model.GetLoginModel;
import cn.doctorpda.conference.model.IPostModel;
import cn.doctorpda.conference.okhttp.callback.StringCallback;
import cn.doctorpda.conference.utils.AESUtil;
import cn.doctorpda.conference.utils.GsonUtil;
import cn.doctorpda.conference.utils.L;
import cn.doctorpda.conference.view.callbackview.IBaseView;
import cn.doctorpda.conference.view.callbackview.ILoginView;
import okhttp3.Call;

/**
 * Created by huangjinlong on 2016/5/19.
 */
public class LoginPresenter {
    private IPostModel model;
    private ILoginView loginView;

    public LoginPresenter(ILoginView baseView) {
        model = new GetLoginModel();
        loginView = baseView;
    }

    public void getLoginData(String number, String password) {
        model.postNetWorkStringData(NetConfig.GET_LOGIN, new StringCallback() {
            @Override
            public void onError(Call call, Exception e) {
                loginView.setLoginError(call, e);
            }

            @Override
            public void onResponse(String response) {
                try {
                    Msg msg = GsonUtil.fromJson(response, Msg.class);
                    loginView.setILoginToast(msg);//放前面才弹吐司？？
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.has("encrpt_flag")) {
                        if (jsonObject.getString("encrpt_flag").equals("1")) {
                            String data = AESUtil.decrypt(msg.getData(), AppConfig.AES_KEY);
                            JSONObject object = new JSONObject(data);
                            L.d(object.getString("account"));
                            User user = GsonUtil.fromJson(object.getString("account"), User.class);
                            ClientInfo.setUserAccessToken(MyApplication.getInstance(), object.getString("access_token"));
                            UserInfo.clearUser();
                            UserInfo.saveUserInfo(user);
                            loginView.setLoginResult(msg, user);
                        }
                    } else {
                        loginView.setLoginResult(msg, null);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, number, password);
    }
}
